import django_filters
from rest_framework import filters
from django.db.models import Q

from apps.club_system.club.models import ClubQuit, ClubApplication, ClubCancel, Club, ClubMember

# 自定义过滤器，根据url中的参数返回对应的内容
# 退出社团表过滤器
from apps.common.account.models import Account


class ClubQuitFilter(django_filters.rest_framework.FilterSet):
    account_id = django_filters.CharFilter()
    club_id = django_filters.CharFilter()

    class Meta:
        model = ClubQuit
        fields = ['account_id', 'club_id']


# 申请加入社团表过滤器
class ClubApplicationFilter(django_filters.rest_framework.FilterSet):
    account_id = django_filters.CharFilter()
    club_id = django_filters.CharFilter()
    club = django_filters.CharFilter(field_name='club__name', lookup_expr='icontains')

    class Meta:
        model = ClubApplication
        fields = ['account_id', 'club', 'club_id', 'first_check_status', 'second_check_status']


# 社团表过滤器
class ClubFilter(django_filters.rest_framework.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    president = django_filters.CharFilter(method='filter_account')

    class Meta:
        model = Club
        fields = ['name', 'business_unit_id', 'president', 'is_active', 'second_check_status', 'type']

    def filter_account(self, queryset, name, value):
        # 获取该会长管理的社团
        print(value)
        club_qs = ClubMember.objects.filter(account__realname__icontains=value, role=3, is_active=True) \
            .values_list('club_id', flat=True)
        print(club_qs)
        club_ids = [id for id in club_qs]
        print(club_ids)
        return queryset.filter(id__in=club_ids)


# 注销表过滤器
class ClubCancelFilter(django_filters.rest_framework.FilterSet):
    club = django_filters.CharFilter(field_name='club__name', lookup_expr='icontains')
    club_id = django_filters.CharFilter()
    account_id = django_filters.CharFilter()

    class Meta:
        model = ClubCancel
        fields = ['account_id', 'club', 'club_id']


class AccountFilter(django_filters.rest_framework.FilterSet):
    search_key = django_filters.CharFilter(method="filter_search_key")
    search = django_filters.CharFilter(method="filter_search")
    faculty_title = django_filters.CharFilter(field_name='faculty_title', lookup_expr='icontains')
    username = django_filters.CharFilter(field_name='username', lookup_expr='icontains')
    realname = django_filters.CharFilter(field_name='realname', lookup_expr='icontains')
    type = django_filters.CharFilter(field_name='type', lookup_expr='icontains')

    @staticmethod
    def filter_search_key(queryset, name, value):
        return queryset.filter(Q(username__icontains=value) | Q(realname__icontains=value))

    @staticmethod
    def filter_search(queryset, name, value):
        return queryset.filter(Q(username=value) | Q(realname=value))

    class Meta:
        model = Account
        fields = ('id', 'faculty_code', 'username', 'realname', 'faculty_title', 'type',)
